package demo.IOStream;

import com.sun.corba.se.impl.orbutil.ObjectWriter;


import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/15-08-15-22:06
 * @Description：demo.IOStream
 */
/*
创建Teacher类，属性包含id,name,salary
从控制台输入教师基本信息，数据之间通过“ - ”分割(每一行，为一个老师的信息)，当输入exit时 结束
从控制台获取教师信息后创建教师对象，将对象添加到集合中
将集合写到文件中
再从文件中读取集合进行遍历输出
 */
public class Object_Teacher {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        ArrayList<Teacher> list = new ArrayList<>();

        Scanner sc = new Scanner(System.in);
        String str = null;
        while(!(str= sc.nextLine()).equals("exit")){
            String[] s = str.split("-");
            int id = Integer.valueOf(s[0]);
            String name = s[1];
            int salary = Integer.valueOf(s[2]);

            list.add(new Teacher(id,name,salary));
        }
        try {
            oos = new ObjectOutputStream(new FileOutputStream("Object.txt"));
            oos.writeObject(list);
            oos.flush();

            ois = new ObjectInputStream(new FileInputStream("Object.txt"));
            list = (ArrayList<Teacher>) ois.readObject();
            for (Teacher teacher : list) {
                System.out.println(teacher);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                if(oos != null){
                    oos.close();
                }
                if(ois != null){
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
class Teacher implements Serializable {
    private int id;
    private String name;
    private int salary;

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public Teacher(int id, String name, int salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
}
